package com.lyp.lease.web.admin.custom.interceptor;

import com.lyp.lease.common.context.LoginUser;
import com.lyp.lease.common.context.LoginUserContext;
import com.lyp.lease.common.exception.LeaseException;
import com.lyp.lease.common.result.ResultCodeEnum;
import com.lyp.lease.common.utils.JwtUtil;
import com.lyp.lease.web.admin.vo.system.user.SystemUserInfoVo;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    //

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRemoteAddr());

        String token = request.getHeader("access_token");
        if (token==null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        } else {
            // 自己写的工具类，判断Token是否正确，如果不正确就会抛出异常，能执行完这行代码，说明就没问题
            Claims claims = JwtUtil.parseToken(token);

            Long userid = claims.get("userid", Long.class);
            String username = claims.get("username", String.class);
            LoginUserContext.setLoginUser(new LoginUser(userid,username));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空threadLocal内容
        LoginUserContext.removeContext();
    }
}
